package com.lianxueda.drawing.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lianxueda.drawing.domain.dto.CourseQueryDTO;
import com.lianxueda.drawing.domain.pojo.*;
import com.lianxueda.drawing.domain.vo.CourseClassVO;
import com.lianxueda.drawing.domain.vo.CourseVO;
import com.lianxueda.drawing.domain.vo.PageVO;
import com.lianxueda.drawing.mapper.*;
import com.lianxueda.drawing.service.CoursesService;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @author 29264
* @description 针对表【courses】的数据库操作Service实现
* @createDate 2024-08-16 14:33:13
*/
@Service
public class CoursesServiceImpl extends ServiceImpl<CoursesMapper, Courses>
    implements CoursesService{

    @Resource
    private CoursesMapper courseMapper;
    @Resource
    private ClassMapper classMapper;

    @Resource
    private ClassCoursesMapper classCoursesMapper;

    @Resource
    private SchedulesMapper schedulesMapper;


    @Resource
    private StudentsMapper studentMapper;
    @Resource
    private CourseStudentMapper courseStudentMapper;

    @Override
    public PageVO<CourseClassVO> searchPage(CourseQueryDTO dto) {
        LambdaQueryWrapper<Courses> queryCondition = new LambdaQueryWrapper<>();
        queryCondition.ne(Courses::getDeleted, 1);
        queryCondition.like(StringUtils.hasText(dto.getName()), Courses::getName, dto.getName());

        if (dto.getStartValidityTime() != null) {
            queryCondition.apply("date_format(course_validity,'%Y-%m-%d') >= {0}", dto.getStartValidityTime());
        }

        if (dto.getEndValidityTime() != null) {
            queryCondition.apply("date_format(course_validity,'%Y-%m-%d') <= {0}", dto.getEndValidityTime());
        }
        IPage<Courses> page = new Page<>(dto.getCurPage(), dto.getPageSize());
        queryCondition.orderByDesc(Courses::getId);
        queryCondition.select(Courses.class, info ->!info.getColumn().equals("deleted"));
        IPage<Courses> pageResult = courseMapper.selectPage(page, queryCondition);

        // 获取课程列表并查询对应的班级名称
        List<Courses> coursesList = pageResult.getRecords();
        List<CourseClassVO> courseClassVOList = new ArrayList<>();
        for(Courses course : coursesList){
            CourseClassVO courseClassVO = new CourseClassVO();
            BeanUtils.copyProperties(course, courseClassVO);
            // 查询班级名称
            String className = classMapper.selectClassNameByCourseId(course.getId());
            courseClassVO.setClassName(className);
            courseClassVOList.add(courseClassVO);
        }





        PageVO<CourseClassVO> pageVO = new PageVO<>();
        pageVO.setCurrentPage(pageResult.getCurrent());
        pageVO.setPageSize(pageResult.getSize());
        pageVO.setTotal(pageResult.getTotal());
        pageVO.setList(courseClassVOList);
        return pageVO;

    }

    @Override
    public Courses getCoursesById(Integer id) {

        return courseMapper.selectByStudentId(id);
    }

    @Override
    public List<Courses> selectCourseByIds(List<Integer> courseIds) {

        return courseMapper.selectCourseByIds(courseIds);
    }

    @Override
    public Integer getCourseIdByName(String name) {

        return courseMapper.selectCourseIdByName(name);
    }

    @Override
    public List<Courses> selectCourseById(Integer classId) {
        // 从联合表中获取 courseIds 列表
        List<Integer> courseIds = classCoursesMapper.selectCourseIdsByClassId(classId);

        // 根据 courseId 列表获取课程对象列表
        return courseMapper.selectCourseByIds(courseIds);

    }

//    @Override
//    public List<Courses> getAllCoursesWithSchedules() {
//        List<Courses> coursesList = this.list(); // 获取所有课程
//        for (Courses course : coursesList) {
//            List<Schedules> schedules = schedulesMapper.selectList(
//                    new QueryWrapper<Schedules>().eq("course_id", course.getId())
//            );
//            course.setSchedules(schedules);
//        }
//        return coursesList;
//    }

    // 在 CoursesService 实现类中

//    @Override
//    public List<Courses> getAllCoursesWithSchedules() {
//        // 1. 获取所有课程
//        List<Courses> coursesList = this.list();
//
//        // 2. 从课程列表中提取所有的课程 ID
//        List<Integer> courseIds = coursesList.stream()
//                .map(Courses::getId)
//                .collect(Collectors.toList());
//
//        if (courseIds.isEmpty()) {
//            // 如果没有课程 ID，直接返回空课程列表
//            return coursesList;
//        }
//
//        // 3. 查询 class_courses 表，获取与这些课程相关的班级 ID
//        List<ClassCourses> classCoursesList = classCoursesMapper.selectByCourseIds(courseIds);
//
//        // 4. 创建 Map，存储每个 course_id 对应的 class_id
//        Map<Integer, Integer> courseIdToClassIdMap = new HashMap<>();
//        for (ClassCourses classCourse : classCoursesList) {
//            if (classCourse != null && classCourse.getCourseId() != null) {
//                courseIdToClassIdMap.put(classCourse.getCourseId(), classCourse.getClassId());
//            }
//        }
//
//        // 5. 从 class_courses 表中提取所有 class_id
//        List<Integer> classIds = new ArrayList<>(courseIdToClassIdMap.values());
//
//        // 6. 查询 classes 表，获取所有这些班级的名称
//        if (classIds.isEmpty()) {
//            for (Courses course : coursesList) {
//                course.setClassName("暂无分配班级");
//            }
//        } else {
//            List<Classes> classesList = classMapper.selectList(new QueryWrapper<Classes>().in("id", classIds));
//
//            // 为每个课程设置班级名称
//            for (Courses course : coursesList) {
//                Integer classId = courseIdToClassIdMap.get(course.getId());
//                String className = null;
//                if (classId != null) {
//                    for (Classes cls : classesList) {
//                        if (cls.getId().equals(classId)) {
//                            className = cls.getName();
//                            break;
//                        }
//                    }
//                }
//                course.setClassName(className);
//            }
//        }
//
//        // 7. 获取所有课表
//        List<Schedules> allSchedules = schedulesMapper.selectList(null);
//
//        // 8. 创建 Map，存储每个 course_id 对应的所有课表
//        Map<Integer, List<Schedules>> scheduleMap = new HashMap<>();
//        for (Schedules schedule : allSchedules) {
//            if (schedule != null) {
//                scheduleMap
//                        .computeIfAbsent(schedule.getCourseId(), k -> new ArrayList<>())
//                        .add(schedule);
//            }
//        }
//
//        // 9. 为每个课程设置对应的课表
//        for (Courses course : coursesList) {
//            course.setSchedules(scheduleMap.getOrDefault(course.getId(), new ArrayList<>()));
//        }
//
//        // 10. 查询 course_student 表，获取与这些课程相关的学生 ID
//        List<CourseStudent> courseStudentList = courseStudentMapper.selectByCourseIds(courseIds);
//
//        // 11. 创建 Map，存储每个 course_id 对应的 student_ids
//        Map<Integer, List<Integer>> courseIdToStudentIdsMap = new HashMap<>();
//        for (CourseStudent courseStudent : courseStudentList) {
//            if (courseStudent != null && courseStudent.getCourseId() != null) {
//                courseIdToStudentIdsMap
//                        .computeIfAbsent(courseStudent.getCourseId(), k -> new ArrayList<>())
//                        .add(courseStudent.getStudentId());
//            }
//        }
//
//        // 12. 从 student_ids 中提取所有 student_id
//        List<Integer> studentIds = courseStudentList.stream()
//                .map(CourseStudent::getStudentId)
//                .collect(Collectors.toList());
//
//        if (!studentIds.isEmpty()) {
//            // 13. 查询 students 表，获取所有这些学生的姓名
//            List<Students> studentsList = studentMapper.selectList(new QueryWrapper<Students>().in("id", studentIds));
//
//            // 14. 创建 Map，存储 student_id 对应的 student_name
//            Map<Integer, String> studentIdToNameMap = studentsList.stream()
//                    .collect(Collectors.toMap(Students::getId, Students::getName));
//
//            // 15. 为每个课程设置对应的 studentNames 列表
//            for (Courses course : coursesList) {
//                List<Integer> studentIdsForCourse = courseIdToStudentIdsMap.get(course.getId());
//                if (studentIdsForCourse != null) {
//                    List<String> studentNames = studentIdsForCourse.stream()
//                            .map(studentIdToNameMap::get)
//                            .collect(Collectors.toList());
//                    course.setStudentNames(studentNames);
//                } else {
//                    course.setStudentNames(new ArrayList<>());
//                }
//            }
//        }
//
//        // 16. 返回课程列表
//        return coursesList;
//    }

    @Override
    public List<Courses> getAllCoursesWithSchedules() {
        // 1. 获取所有课程
        List<Courses> coursesList = this.list();

        // 2. 从课程列表中提取所有的课程 ID
        List<Integer> courseIds = coursesList.stream()
                .map(Courses::getId)
                .collect(Collectors.toList());

        if (courseIds.isEmpty()) {
            // 如果没有课程 ID，直接返回空课程列表
            return coursesList;
        }

        // 3. 查询 class_courses 表，获取与这些课程相关的班级 ID
        List<ClassCourses> classCoursesList = classCoursesMapper.selectByCourseIds(courseIds);

        // 4. 创建 Map，存储每个 course_id 对应的 class_id
        Map<Integer, Integer> courseIdToClassIdMap = new HashMap<>();
        for (ClassCourses classCourse : classCoursesList) {
            if (classCourse != null && classCourse.getCourseId() != null) {
                courseIdToClassIdMap.put(classCourse.getCourseId(), classCourse.getClassId());
            }
        }

        // 5. 从 class_courses 表中提取所有 class_id
        List<Integer> classIds = new ArrayList<>(courseIdToClassIdMap.values());

        // 6. 查询 classes 表，获取所有这些班级的名称
        if (classIds.isEmpty()) {
            for (Courses course : coursesList) {
                course.setClassName("暂无分配班级");
            }
        } else {
            List<Classes> classesList = classMapper.selectList(new QueryWrapper<Classes>().in("id", classIds));

            // 为每个课程设置班级名称
            for (Courses course : coursesList) {
                Integer classId = courseIdToClassIdMap.get(course.getId());
                String className = null;
                if (classId != null) {
                    for (Classes cls : classesList) {
                        if (cls.getId().equals(classId)) {
                            className = cls.getName();
                            break;
                        }
                    }
                }
                course.setClassName(className);
            }
        }

        // 7. 获取所有课表
        List<Schedules> allSchedules = schedulesMapper.selectList(null);

        // 8. 创建 Map，存储每个 course_id 对应的所有课表
        Map<Integer, List<Schedules>> scheduleMap = new HashMap<>();
        for (Schedules schedule : allSchedules) {
            if (schedule != null) {
                scheduleMap
                        .computeIfAbsent(schedule.getCourseId(), k -> new ArrayList<>())
                        .add(schedule);
            }
        }

        // 9. 为每个课程设置对应的课表
        for (Courses course : coursesList) {
            course.setSchedules(scheduleMap.getOrDefault(course.getId(), new ArrayList<>()));
        }

        // 10. 查询 course_student 表，获取与这些课程相关的学生 ID
        List<CourseStudent> courseStudentList = courseStudentMapper.selectByCourseIds(courseIds);

        // 11. 创建 Map，存储每个 course_id 对应的 student_ids
        Map<Integer, List<Integer>> courseIdToStudentIdsMap = new HashMap<>();
        for (CourseStudent courseStudent : courseStudentList) {
            if (courseStudent != null && courseStudent.getCourseId() != null) {
                courseIdToStudentIdsMap
                        .computeIfAbsent(courseStudent.getCourseId(), k -> new ArrayList<>())
                        .add(courseStudent.getStudentId());
            }
        }

        // 12. 从 student_ids 中提取所有 student_id
        List<Integer> studentIds = courseStudentList.stream()
                .map(CourseStudent::getStudentId)
                .collect(Collectors.toList());

        if (!studentIds.isEmpty()) {
            // 13. 查询 students 表，获取所有这些学生的对象
            List<Students> studentsList = studentMapper.selectList(new QueryWrapper<Students>().in("id", studentIds));

            // 14. 创建 Map，存储 student_id 对应的 student 对象
            Map<Integer, Students> studentIdToStudentMap = studentsList.stream()
                    .collect(Collectors.toMap(Students::getId, student -> student));

            // 15. 为每个课程设置对应的学生对象列表
            for (Courses course : coursesList) {
                List<Integer> studentIdsForCourse = courseIdToStudentIdsMap.get(course.getId());
                if (studentIdsForCourse != null) {
                    List<Students> studentObjects = studentIdsForCourse.stream()
                            .map(studentIdToStudentMap::get)
                            .collect(Collectors.toList());
                    course.setStudents(studentObjects);
                } else {
                    course.setStudents(new ArrayList<>());
                }
            }
        }

        // 16. 返回课程列表
        return coursesList;
    }



    @Override
    public List<Courses> selectCoursesByIds(List<Integer> coursesIdList) {
        return courseMapper.selectCoursesByIds(coursesIdList);
    }

}




